<template>
  <el-dialog class="register" width="600px" :visible="isShow" :show-close="false">
    <!-- 重新对话框头部 -->
    <div slot="title" class="register-title">用户注册</div>
    <!-- 对话框内容 -->
    <div class="content">
      <!-- 设置验证 -->
      <el-form ref="form" class="form" :model="form" :rules="rules" label-width="70px">
        <el-form-item prop="avatar" label="头像">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            name="image"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item prop="username" label="昵称">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item prop="phone" label="手机">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item prop="pcode" label="图形码">
          <el-row>
            <el-col :span="14">
              <el-input v-model="form.pcode"></el-input>
            </el-col>
            <el-col :span="9" :offset="1">
              <img class="register-codeImg" v-if="bol" @click="updatepcode" :src="pcodeUrl" alt />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item prop="rcode" label="验证码">
          <el-row>
            <el-col :span="14">
              <el-input v-model="form.rcode"></el-input>
            </el-col>
            <el-col :span="9" :offset="1">
              <!-- disabled属性的值为 true时,按钮禁用。 为false时，按钮不禁用 -->
              <el-button @click="getrcode" class="getrcode" :disabled="totalTime<5">
                <span>获取用户验证码</span>
                <span v-if="totalTime!=5">({{totalTime + 1}}秒)</span>
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </div>
    <!-- 重新对话框底部 -->
    <div slot="footer" class="register-footer">
      <el-button @click="isShow=false">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </div>
  </el-dialog>
</template>
<script>
// import axios from "axios";
import { getRcode, registerUser } from "@/api/register";
export default {
  data() {
    return {
      totalTime: 5, // 验证码按钮总时间
      isShow: false, // 注册面板是否显示
      imageUrl: "", // 图片预览
      pcodeUrl: process.env.VUE_APP_URL + "/captcha?type=sendsms", // 图形码接口地址
      uploadUrl: process.env.VUE_APP_URL + "/uploads", // 上传头像接口地址
      bol: true, // 图形验证码局部刷新
      form: {
        avatar: "", //	是	string	头像地址
        username: "", //	是	string	用户名
        email: "", //	是	string	邮箱
        phone: "", //	是	string	手机号
        password: "", //	是	string	密码
        pcode: "",
        rcode: "" //	是	string	验证码
      },
      rules: {
        avatar: [{ required: true, message: "请选择头像", trigger: "change" }],
        username: [
          { required: true, message: "请输入用户名", trigger: "change" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "change" },
          {
            validator(rule, value, callback) {
              let _email = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
              if (_email.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确的邮箱地址"));
              }
            },
            trigger: "change"
          }
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "change" },
          {
            validator(rule, value, callback) {
              let _phone = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
              if (_phone.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确的电话号码"));
              }
            },
            trigger: "change"
          }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "change" },
          { min: 6, max: 12, message: "请输入6-12位密码", trigger: "change" }
        ],
        pcode: [
          { required: true, message: "请输入验证码", trigger: "change" },
          { min: 4, max: 4, message: "请输入4位数验证码", trigger: "change" }
        ],
        rcode: [
          { required: true, message: "请输入短信验证码", trigger: "change" }
        ]
      }
    };
  },
  watch: {
    isShow(newVal) {
      if (newVal === false) {
        this.$refs.form.resetFields();
        this.imageUrl = "";
      }
    }
  },
  methods: {
    // 获取短信验证码事件
    getrcode() {
      // 调用el-form的validateField 方法，验证部分字段名
      // 声明一个箩筐
      let num = 0;
      this.$refs.form.validateField(["phone", "pcode"], error => {
        if (error == "") {
          // error为空则验证成功
          num++;
        }
      });
      // 如果num==2 说明手机号与图形验证码的验证都通过了
      if (num == 2) {
        // 进到这里 说明图形验证码与手机号都验证成功，可以调用接口发生请求
        /*
          发送短信验证码请求:
          1. 安装axios
          2.导入axios
          3.使用axios
        */
        // 设置获取验证码按钮节流
        // 当用户点击后totalTime 立即--
        this.totalTime--;
        let timeId = setInterval(() => {
          this.totalTime--;
          if (this.totalTime <= -1) {
            clearInterval(timeId);
            this.totalTime = 5;
          }
        }, 1000);

        // 发送axios获取短信验证码
        getRcode({ code: this.form.pcode, phone: this.form.phone }).then(
          res => {
            window.console.log(res);
            // TypeError: Cannot create property 'type' on number '1397'
            // $nessage里的内容不可以为Number
            // 在限制一下，如果验证码错误就不提示
            this.$message.success(res.data.captcha + "");
          }
        );
      } else {
        // 进到这里说明用户手机号或者图形验证码不通过
        this.$message.error("验证不通过");
      }
    },

    // 点击图形验证码图片更新图片
    updatepcode() {
      // 利用v-if控制pcode图片是否渲染的机制
      this.bol = false;
      // 设置一个异步任务
      this.$nextTick(() => {
        // $nextTick内部会帮我们自动计算数据渲染到页面上的时间，
        // 当页面数据渲染完成就会执行$nextTick里的代码
        this.bol = true;
      });
    },

    // 提交按钮确定
    submit() {
      this.$refs.form.validate(result => {
        if (result) {
          // this.$message.success("验证成功!");
          registerUser(this.form).then(res => {
            window.console.log("注册成功:", res);

            // 提示用户注册成功
            this.$message.success("恭喜您,注册成功!");
            // 注册成功关闭注册面板
            this.isShow = false;
          });
        } else {
          this.$message.error("验证失败");
        }
      });
    },
    /* 
       // 值已保存至form下
      this.form.avatar = res.data.file_path
      // 人为触发一下avatar的表单验证
      // 调用子组件方法  1：在子组件定义ref   2:this.$refs.值.validateField(['avatar(写出需要验证的字段名)'],error=>{error:错误信息，error的值就是验证不通过，error为空表示验证通过})
      this.$refs.form.validateField(['avatar'], errorMessage => {
        window.console.log('avatar错误信息:', errorMessage)
      })
    */
    // 上传成功后显示该图片
    handleAvatarSuccess(res) {
      this.form.avatar = res.data.file_path;
      // 注意！ 这里的res.data.file_path 是相对路径，需要跟基地址进行拼接
      // el-form组件实例中有一个validateFiled方法，  可以对部分表单字段进行效验z
      this.$refs.form.validateField(["avatar"], error => {
        window.console.log(error);
      });
      this.imageUrl = process.env.VUE_APP_URL + "/" + res.data.file_path;
    },
    // 设置图片限制
    beforeAvatarUpload(file) {
      let typeIsPass = file.type === "image/jpeg" || file.type === "image/png";
      let isLt2M = file.size / 1024 / 1024 < 2;

      if (!typeIsPass) {
        this.$message.error("上传头像图片只能是 JPG,PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return typeIsPass && isLt2M;
    }
  }
};
</script>
<style lang='less'>
.register {
  .el-dialog__header {
    padding: 0;
  }
  .register-title {
    text-align: center;
    background: linear-gradient(to right, #01c4fa, #1394fa);
    height: 53px;
    line-height: 53px;
  }
  .register-footer {
    text-align: center;
  }
  .content {
    .form {
      .avatar-uploader {
        text-align: center;
        .el-upload {
          border: 1px dashed #ccc;
          border-radius: 6px;
          cursor: pointer;
          position: relative;
          overflow: hidden;
          width: 179px;
          height: 179px;
          line-height: 179px;
          .avatar-uploader-icon {
            font-size: 28px;
          }
          .el-icon-plus:before {
            font-weight: 100;
            color: #abb0b7;
          }
          .avatar {
            width: 179px;
            height: 179px;
            display: block;
          }
        }
        .el-upload:hover {
          border-color: #409eff;
        }
      }
    }
  }
  .register-codeImg {
    width: 100%;
    height: 40px;
  }
}
</style>